package com.efounder.util;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import androidx.appcompat.app.AlertDialog;

import android.util.Log;

import com.efounder.chat.db.GetDBHelper;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.service.OSPService;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.service.WatchService;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.socket.JFSocketManager;
import com.efounder.ospmobilelib.R;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ActivityUtils;
import com.utilcode.util.AppUtils;
import com.utilcode.util.StringUtils;
import com.zhuiji7.filedownloader.download.DownLoadService;

import java.util.HashMap;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;


/**
 * 退出下线 注销登录
 *
 * @author YQS
 */
public class LogOutUtil {
    private static final String TAG = "LogOutUtil";

    /**
     * 停止消息推送服务
     *
     * @param reqCallBack
     */
    public static void stopPushMessage(JFCommonRequestManager.ReqCallBack<String> reqCallBack) {

        //不支持消息推送 调用成功
//        if (!MobilePushUtils.isSupportPush()) {
//            if (reqCallBack != null) {
//                reqCallBack.onReqSuccess("success");
//            }
//            return;
//        }
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID, ""));
        paramMap.put("passWord", EnvironmentVariable.getProperty(CHAT_PASSWORD, ""));
        paramMap.put("deviceId", MessageService.getDeviceId(AppContext.getInstance()));
        paramMap.put("subAppId", EnvironmentVariable.getProperty("subAppId", ""));
        JFCommonRequestManager.getInstance(AppContext.getInstance()).requestGetByAsyn(
                TAG, GetHttpUtil.ROOTURL + "/IMServer/user/logout", paramMap, reqCallBack);
    }

    //应用下线
    public static void notifyOffline(final LogoutEvent event) {
//        LogUtils.e(ActivityUtils.getTopActivity().getClass().getSimpleName());
        showLogoutTips(event);

        stopPushMessage(new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
//                showLogoutTips(event);
//                try {
////                    ActivityCompat.finishAffinity(getActivity());
//                    Intent intent = new Intent(ActivityUtils.getTopActivity(), Class.forName("com.efounder.activity.Login_withTitle"));
//                    intent.putExtra("logOut", true);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                    ActivityUtils.getTopActivity().startActivity(intent);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
//                showLogoutTips(event);
            }
        });

    }

    /**
     * 显示下线提示
     */
    private static void showLogoutTips(LogoutEvent event) {
        if (ActivityUtils.getTopActivity() == null) {
            return;
        }

        //1.关闭消息链接 关闭TCP链接
//        JFSocketManager.getInstance().stop();
        try {
            CommonThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    JFSocketManager.getInstance().stop();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


        stopPushMessage(null);
        EnvironmentVariable.setPassword("");//清空登录密码密码

        EnvironmentVariable.setProperty(CHAT_PASSWORD, "");//清空消息密码
        if (event != null && event.getType() == LogoutEvent.TYPE_DEFAULT) {
            //默认 停止服务 重启应用
            stopLocalIMService(ActivityUtils.getTopActivity());
            AppUtils.relaunchApp();
        } else if (event != null && event.getType() == LogoutEvent.TYPE_LOGIN_OUT_OF_DATE) {
            String msg = event.getMsg();
            if (StringUtils.isEmpty(msg)) {
                msg = ResStringUtil.getString(R.string.common_text_login_out_of_date);
            }
            //todp登录过期失效，重新登录
            new AlertDialog.Builder(ActivityUtils.getTopActivity())
                    .setTitle(R.string.common_text_hint)
                    .setMessage(msg)
                    .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            stopLocalIMService(ActivityUtils.getTopActivity());
                            AppUtils.relaunchApp();
                        }
                    })
                    .setCancelable(false)
                    .create().show();

            return;
        }
        //应用被强制下线
        final AlertDialog.Builder builder = new AlertDialog.Builder(ActivityUtils.getTopActivity());
        builder.setMessage(ResStringUtil.getString(R.string.wechat_comps_logout_dialog_forced_offline));
        builder.setTitle(ResStringUtil.getString(R.string.wechat_comps_logout_dialog_offline_notify));
        builder.setCancelable(false);
        builder.setPositiveButton(ResStringUtil.getString(R.string.wechat_comps_logout_dialog_exit), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                //finishiAffinity()的使用场景是：关闭你当前activity所在栈中的所有的activity
                ActivityUtils.getTopActivity().finishAffinity();
                stopLocalIMService(ActivityUtils.getTopActivity());
                stopPushMessage(null);
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);

            }
        });

        builder.setNegativeButton(ResStringUtil.getString(R.string.wechat_comps_logout_dialog_re_register), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                arg0.dismiss();
                stopLocalIMService(ActivityUtils.getTopActivity());
                stopPushMessage(null);
                AppUtils.relaunchApp();
            }
        });
        builder.create().show();

    }

    /**
     * 停止本地消息服务
     */
    public static void stopLocalIMService(Context context) {
        //1.关闭消息链接 关闭TCP链接
//        JFSocketManager.getInstance().stop();
        try {
            CommonThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    JFSocketManager.getInstance().stop();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        //释放JFMessageManager
        try {
            JFMessageManager.dealloc();
            //2停止serviece
            releaseService(context);
            //3关闭数据库
            GetDBHelper.getInstance().release();
            //4.取消推送
            stopPushMessage(null);
            //5清空密码
            clearLoginInfo();
            //6取消自动登录状态
            clearState();
        } catch (Exception e) {
        }
    }

    /**
     * 停止应用的相关服务
     *
     * @param context
     */
    public static void releaseService(Context context) {
        Log.i(TAG, "releaseService");
        context.stopService(new Intent(context, OSPService.class));
        context.stopService(new Intent(context, WatchService.class));
        context.stopService(new Intent(context, MessageService.class));
        context.stopService(new Intent(context, SystemInfoService.class));
        context.stopService(new Intent(context, DownLoadService.class));
    }


    /**
     * 清除登录密码，消息账号密码信息
     */
    public static void clearLoginInfo() {
        EnvironmentVariable.setPassword("");//清空登录密码密码

        //清空用户名 userID = CHAT_USER_ID，在 LoginManager 中存入,也是消息id
        EnvironmentVariable.setUserID("");
        EnvironmentVariable.setProperty(Constants.CHAT_USER_ID, "");
        EnvironmentVariable.setProperty(CHAT_PASSWORD, "");//清空IM登录密码密码

    }

    /**
     * 取消自动登录设置
     */
    private static void clearState() {
        StorageUtil storageUtil = new StorageUtil(AppContext.getInstance(), "storage");
        storageUtil.putBoolean("isAuto", false);
        storageUtil.putBoolean("isSave", false);
        storageUtil.commit();
    }
}
